<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.adStatus" clearable class="filter-item" style="width: 200px;" placeholder="请输入店铺ID"/>
      <el-input v-model="listQuery.adLocationType" clearable class="filter-item" style="width: 200px;" placeholder="请输入店铺名称"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button> -->
      <el-button class="filter-item" size="mini" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <!-- <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" border size="mini" element-loading-text="正在查询中。。。" highlight-current-row>

      <!--<el-table-column align="center" label="轮播位置" prop="adLocationType"/>-->

      <el-table-column align="center" label="介绍" prop="adIntroduce"/>

      <el-table-column align="center" label="跳转链接" prop="linkUrl"/>

      <el-table-column align="center" label="广告图片" prop="picUrl" width="200px">
        <template slot-scope="scope">
          <el-popover placement="right" title="" trigger="hover">
            <img :src="scope.row.picUrl" style="width:300px;height:300px;">
            <img slot="reference" :src="scope.row.picUrl" style="width:120px;">
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column align="center" label="排序" prop="adSort" width="100px"/>

      <el-table-column align="center" label="状态" prop="adStatus" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.adStatus===0" type="info">下架</el-tag>
          <el-tag v-if="scope.row.adStatus===1" type="success">上架</el-tag>
        </template>
      </el-table-column>

      <!--<el-table-column align="center" label="上架时间" prop="putTime"/>
      <el-table-column align="center" label="下架时间" prop="downTime"/>
      <el-table-column align="center" label="创建时间" prop="createDate"/>-->
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.adStatus===0" type="success" size="mini" @click="handleStatus(scope.row,1)">上架</el-button>
          <el-button v-if="scope.row.adStatus===1" type="info" size="mini" @click="handleStatus(scope.row,0)">下架</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <!--<el-form-item label="广告位置" prop="adLocationType">-->
        <!--<el-input v-model="dataForm.adLocationType" type="number"/>-->
        <!--</el-form-item>-->
        <el-form-item label="广告介绍" prop="adIntroduce">
          <el-input v-model="dataForm.adIntroduce"/>
        </el-form-item>
        <el-form-item label="跳转链接" prop="linkUrl">
          <el-input v-model="dataForm.linkUrl"/>
        </el-form-item>
        <el-form-item label="审核" prop="adStatus">
          <el-select v-model="dataForm.adStatus" clearable placeholder="请选择">
            <el-option :value="1" label="上架"/>
            <el-option :value="0" label="下架"/>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="adSort">
          <el-input v-model="dataForm.adSort" type="number"/>
        </el-form-item>
        <el-form-item label="广告图片" prop="picUrl">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="dataForm.picUrl" :src="dataForm.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
        <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button size="mini" v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

<script>
import { listAd, createAd, updateAd, deleteAd } from '@/api/ad'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'AD',
  components: { Pagination },
  data() {
    return {
      uploadPath,
      updateParam: undefined,
      list: undefined,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        id: undefined,
        adLocationType: undefined,
        adIntroduce: undefined,
        picUrl: undefined,
        linkUrl: undefined,
        adStatus: undefined,
        adSort: undefined,
        putTime: undefined,
        downTime: undefined,
        createDate: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [
          { required: true, message: '商家名称不能为空', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listAd(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        adLocationType: undefined,
        adIntroduce: undefined,
        picUrl: undefined,
        linkUrl: undefined,
        adStatus: 1,
        adSort: 50,
        putTime: undefined,
        downTime: undefined,
        createDate: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    uploadPicUrl: function(response) {
      this.dataForm.picUrl = response.data.url
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          console.log(this.dataForm)
          createAd(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }
      })
    },
    handleStatus(parm, status) {
      this.updateParam = Object.assign({}, parm)
      this.updateParam.adStatus = status
      let content = ''
      if (status === 0) {
        content = '是否下架广告？'
      } else {
        content = '是否上架广告！！'
      }
      this.$confirm(content, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (status === 0) {
          updateAd(this.updateParam)
            .then(() => {
              this.$notify.success({
                title: '成功',
                message: '广告已下架'
              })
              // 刷新列表数据
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
              // 刷新列表数据
              this.getList()
            })
        } else {
          updateAd(this.updateParam)
            .then(() => {
              this.$notify.success({
                title: '成功',
                message: '广告已上架'
              })
              // 刷新列表数据
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
              // 刷新列表数据
              this.getList()
            })
        }
      }).catch(() => {
        this.getList()
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateAd(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }
      })
    },
    handleDelete(row) {
      deleteAd(row)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.message
          })
        })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '商家ID',
          '商家名称',
          '介绍',
          '低价',
          '商家图片'
        ]
        const filterVal = ['id', 'name', 'desc', 'floorPrice', 'picUrl']
        excel.export_json_to_excel2(
          tHeader,
          this.list,
          filterVal,
          '商家信息'
        )
        this.downloadLoading = false
      })
    }
  }
}
</script>
